package com.person.controller;

import com.person.common.BaseContext;
import com.person.common.CustomException;
import com.person.common.R;
import com.person.pojo.ShoppingCart;
import com.person.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加到购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        //判断是否是第一次登录
        if (BaseContext.getCurrentId()==null){
            throw new CustomException("登录过期请返回登录");
        }

        //判断是否是第一次添加
        ShoppingCart goods = shoppingCartService.inquire(shoppingCart.getDishId(), shoppingCart.getSetmealId());
        if (goods == null) {
            shoppingCartService.add(shoppingCart);
        } else {
            //重复添加 number++
            shoppingCartService.updateNumber(goods.getId());
        }
        ShoppingCart newGoods = shoppingCartService.inquire(shoppingCart.getDishId(), shoppingCart.getSetmealId());
        return R.success(newGoods);
    }

    /**
     * 显示购物车内容
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> getlist(){
        if (BaseContext.getCurrentId()==null){
            throw new CustomException("登录过期请返回登录");
        }
        return R.success(shoppingCartService.getlist(BaseContext.getCurrentId()));
    }
    /**
     * 删除购物车的食品
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        //查询购物车状态
        ShoppingCart shoppingCart1 = shoppingCartService.inquire(shoppingCart.getDishId(), shoppingCart.getSetmealId());
        //如果套餐或菜品=1，直接删除
//        if (shoppingCart1.getNumber() == 1) {
//            //shoppingCartService.delete(shoppingCart.getDishId(), shoppingCart.getSetmealId());
//
//        }
//        //如果套餐或菜品>1,则number-1
//        if (shoppingCart1.getNumber()>1){
//
//        }
        shoppingCartService.sub(shoppingCart.getDishId(), shoppingCart.getSetmealId(), BaseContext.getCurrentId());
        shoppingCart1=shoppingCartService.inquire(shoppingCart.getDishId(), shoppingCart.getSetmealId());
        return R.success(shoppingCart1);

    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        shoppingCartService.clean(BaseContext.getCurrentId());
        return R.success("清空购物车");
    }
}
